package com.xinshujia.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xinshujia.entity.RoleEntity;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Set;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-11 15:47       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 *     角色持久化
 *     基本查询和分页查询
 */
@Mapper
public interface RoleDao extends BaseMapper<RoleEntity>{
    // 根据用户Id查询该用户拥有的角色（roles）
    @Select("SELECT ar.* FROM auth_role ar, auth_user_role aur WHERE aur.role_id = ar.id AND aur.user_id = #{userId};")
    Set<RoleEntity> getRolesByUid(@Param("userId") Long userId);

    // 删除关联表中的数据
    @Select("DELETE FROM auth_role_resource WHERE role_id = #{roleId};")
    void deleteRelationRoleAndResource(@Param("roleId") Long roleId);

    // 给角色分配资源
    @Insert("<script>" +
            "INSERT INTO auth_role_resource(role_id, resource_id) VALUES " +
            "<foreach collection='resourceIds' item='resourceId' separator=','> " +
            "(#{roleId}, #{resourceId}) " +
            "</foreach> " +
            "</script>")
    int setResourcesForRole(@Param("roleId") Long roleId, @Param("resourceIds") List<Long> resourceIds);

    // 删除关联表中的数据
    @Select("DELETE FROM auth_role_device WHERE role_id = #{roleId};")
    void deleteRelationRoleAndDevice(@Param("roleId") Long roleId);

    // 给角色添加设备
    @Insert("<script>" +
            "INSERT INTO auth_role_device(role_id, device_id) VALUES " +
            "<foreach collection='deviceIds' item='deviceId' separator=','> " +
            "(#{roleId}, #{deviceId}) " +
            "</foreach> " +
            "</script>")
    int setDevicesForRole(@Param("roleId") Long roleId, @Param("deviceIds") List<Long> deviceIds);
}